package com.loongtech.bi.action.admin;

import com.loongtech.bi.manager.system.*;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller("loginAction")
@Scope("session")
public class LoginAction implements java.io.Serializable {
	private static final long serialVersionUID = 2891685544887545925L;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private Session session;
	@Autowired
	private SysUserManager sysUserManager;
	@Autowired
	private SysLogManager sysLogManager;
    @Autowired
    private ConfigManager configManager;

	private String username;
	private String password;
	private boolean isAdmin;

    public static Map<String, String> projects = new LinkedHashMap<>();

    @Autowired
	public void init() throws IOException {
        String un =  request.getParameter("uname") == null ? (request.getAttribute("uname") == null ? (String)request.getSession().getAttribute("redirectusername") : (String)request.getAttribute("uname")) : request.getParameter("uname");
        if (StringUtils.isEmpty(un)) {
            un = username;
        }
        
        // 如果un为空 返回login
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        if (StringUtils.isEmpty(un)){
            
            response.sendRedirect("login.jsf");

            return;
        }

        // 如果userid为空 返回login
        Integer userId = sysUserManager.getUserIdByName(un);
        if(null == userId){
            response.sendRedirect("login.jsf");
            return;
        }
            
        // 如果没有项目访问权限 返回login
        Map<String, String> psMap = Utils.getProjects(configManager.getConfigValueByName(ConfigManager.PROJECT_URL), un, configManager.getConfigValueByName(ConfigManager.PROJECT_NAME));
        if (psMap == null || psMap.size() <= 0) {
             response.sendRedirect("login.jsf");
             return;
        }  
            
        //处理支持sign
        String pd =  request.getParameter("sign") == null ? (request.getAttribute("sign") == null ? (String)request.getSession().getAttribute("redirectpassword") : (String)request.getAttribute("sign")) : request.getParameter("sign");
        if (StringUtils.isEmpty(pd)) {
             pd = password;
         }

		if (StringUtils.isBlank(un) || StringUtils.isBlank(pd)) {
			response.sendRedirect("login.jsf");
			return;
		}

		String time = request.getParameter("time") == null ? (request.getAttribute("time") == null ? (String) request.getSession().getAttribute("redirecttime") : (String) request.getAttribute("time")): request.getParameter("time");
		if (!sysUserManager.login(un, pd, time)) {
			response.sendRedirect("login.jsf");
			return;
		}

		projects.clear();
		projects.putAll(psMap);

		request.getSession().setAttribute("userId", un);
		session.setAdmin(true);
		session.setUserId(userId);
		session.setUserName(un);
		sysLogManager.addLog(un, "登录成功,登录名为:" + un + ",userId=" + userId);

		String selfUrl = configManager.getConfigValueByName(ConfigManager.SELF_URL);
		response.sendRedirect(selfUrl == null ? "https://www.baidu.com/": selfUrl + "/resources/pages/main.jsf?faces-redirect=true");
    }

    public String login() {
		try {
			// 用户名或者密码为空
			if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
				return "login.jsf";
			}
			// 用户名或者密码不对
			if(!sysUserManager.login(username, password, "")){
				return "login.jsf";
			}
			// 获取userId
			Integer userId = sysUserManager.getUserIdByName(username);
			if(null == userId){
				return "login.jsf";
			}

            final String projectname = configManager.getConfigValueByName(ConfigManager.PROJECT_NAME);
            Map<String, String> psMap = Utils.getProjects(configManager.getConfigValueByName(ConfigManager.PROJECT_URL), username, projectname);
            if (psMap == null || psMap.size() <= 0) {
                 projects.clear();
                 psMap = new HashMap<String, String>();
                 psMap.put(StringUtils.isEmpty(projectname) ? "bi" : projectname, "bi");
                 projects.putAll(psMap);
            } else {
                projects.clear();
                projects.putAll(psMap);
            }

			// 用户名密码正确，允许登录
			// 设置httpSession
			request.getSession().setAttribute("userId", username);
			
			// 设置项目内session
			session.setAdmin(true);
			session.setUserId(userId);
			session.setUserName(username);
			sysLogManager.addLog(username, "登录成功,登录名为:"+username+",userId="+userId);

            return "main.jsf?faces-redirect=true";
		} catch(Exception e) {
			return "login.jsf";
		}
	}
	
	/**
	 * 注销登录
	 * @return
	 * @author HivenYang
	 *	@date 2015年5月29日
	 */
	public String logout() {
		//直接跳回到登录界面
		return "login.jsf";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isAdmin() {
		return isAdmin;
	}

	public void setAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}
}